/**
 * 
 */
package component.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author liuboen
 * 
 * since:2012-6-7
 * version:1.0.0
 */
public class TopicReceiver {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// ConnectionFactory ：连接工厂，JMS 用它创建连接
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, "tcp://127.0.0.1:61616");

		Connection connection;
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			Session session = connection.createSession(Boolean.TRUE,
					Session.AUTO_ACKNOWLEDGE);
			Topic topic = session.createTopic("test-topic");
			// 消费者，消息接收者
			MessageConsumer consumer = session.createConsumer(topic);
			consumer.setMessageListener(new MessageListener() {

				public void onMessage(Message message) {

					MapMessage mapMessage = (MapMessage) message;
					if (null != mapMessage) {
						try {
							System.out.println("收到消息：" + mapMessage.getString("tst"));
						} catch (JMSException e) {
							e.printStackTrace();
						}
					}

				}

			});
	          session.commit();
	        /*  consumer.close();
              session.close();
              connection.close();*/
		} catch (JMSException e) {
			e.printStackTrace();
		}
    	

	}

}
